package cn.tedu._08article.controller;

import cn.tedu._08article.base.response.JsonResult;
import cn.tedu._08article.base.response.StatusCode;
import cn.tedu._08article.mapper.ArticleMapper;
import cn.tedu._08article.pojo.dto.UserArticleParam;
import cn.tedu._08article.pojo.dto.UserLoginParam;
import cn.tedu._08article.pojo.entity.Article;
import cn.tedu._08article.pojo.vo.ArticleVO;
import cn.tedu._08article.pojo.vo.UserVO;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpSession;
import lombok.extern.slf4j.Slf4j;
import org.hibernate.validator.constraints.Range;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Slf4j
@RestController
@RequestMapping("v1/user/")
@Tag(name="用户信息管理模块")
public class ArticleController {
    @Autowired
    private ArticleMapper articleMapper;

    @PostMapping("login")
    @Operation(summary = "用户登录功能")
    @ApiOperationSupport(order = 10)
    public JsonResult UserLogin(@RequestBody UserLoginParam userLoginParam, HttpSession session){
        log.debug("开始处理用户登录功能"+userLoginParam);
         UserVO userVO=articleMapper.userLoginById(userLoginParam);
         if(userVO==null){
             return new JsonResult(StatusCode.USERNAME_PASSWORD_ERROR);
         }
        session.setAttribute("user", userVO);
        return JsonResult.ok(userVO);
    }
    @PostMapping("article")
    @Operation(summary = "发布文章")
    @ApiOperationSupport(order=20)
    public JsonResult addArticle(@RequestBody @Validated UserArticleParam userArticleParam, HttpSession session){
        log.debug("开始处理用户发布文章功能"+userArticleParam);
        UserVO userVO=(UserVO)session.getAttribute("user");
        if(userVO==null){
            return new JsonResult(StatusCode.NOT_LOGIN);
        }
        Article article=new Article();
        BeanUtils.copyProperties(userArticleParam,article);
        article.setUserId(userVO.getId());
        log.debug("article="+article);
        articleMapper.addArticle(article);
        return JsonResult.ok();
    }
    @GetMapping("selectByArticleId/{id}")
    @Operation(summary = "查询文章功能")
    @ApiOperationSupport(order = 30)
    @Parameter(name = "id",required = true,description = "文章id")
    public JsonResult selectByArticleId(@PathVariable @Range(min = 1L, max = 100L, message = "文章id范围1-100") Long id,HttpSession session){
        UserVO userVO=(UserVO)session.getAttribute("user");
        if(userVO==null){
            return new JsonResult(StatusCode.NOT_LOGIN);
        }
        List<ArticleVO> list=articleMapper.selectArticle(id);
        return JsonResult.ok(list);

    }

}
